import { Button, Card, notification, Popconfirm } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { isNil } from 'ramda';
import { useEffect, useState } from 'react';

import menuService from '@/api/services/security/menuService';
import { Iconify, SvgIcon } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import ProTag from '@/theme/antd/components/tag';
import { hasPermission } from '@/utils/permission';

import MenuModal, { MenuModalProps } from './menu-modal';

import { Menu, Operation } from '#/entity';
import { BasicStatus, MenuType } from '#/enum';
import { menuTypeMapText } from '#/publicVariable';

const defaultMenuValue: Menu = {
  name: '',
  route: '',
  component: '',
  icon: '',
  isHidden: false,
  status: BasicStatus.ENABLE,
  type: MenuType.CATALOGUE,
};

export default function PermissionPage() {
  const [tableData, setTableData] = useState<Menu[]>();
  const [menuModalProps, setMenuModalProps] = useState<MenuModalProps>({
    formValue: { ...defaultMenuValue },
    title: 'New',
    show: false,
    menus: tableData!,
    onOk: () => {
      setMenuModalProps((prev) => ({ ...prev, show: false }));
      menuService.menuList({}).then((res) => {
        setTableData(res);
      });
    },
    onCancel: () => {
      setMenuModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  useEffect(() => {
    menuService.menuList({}).then((res) => {
      setTableData(res);
      setMenuModalProps((prev) => ({ ...prev, menus: res }));
    });
  }, []);
  const columns: ColumnsType<Menu> = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 300,
    },
    {
      title: '类型',
      dataIndex: 'type',
      align: 'left',
      width: 80,
      render: (_, record) => <ProTag color="processing">{menuTypeMapText[record.type]}</ProTag>,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      width: 60,
      render: (icon: string) => {
        if (isNil(icon)) return '';
        if (icon.startsWith('ic')) {
          return <SvgIcon icon={icon} size={18} className="ant-menu-item-icon" />;
        }
        return <Iconify icon={icon} size={18} className="ant-menu-item-icon" />;
      },
    },
    {
      title: '路由',
      dataIndex: 'route',
    },
    {
      title: '组件地址',
      dataIndex: 'component',
    },
    {
      title: '权限标识',
      dataIndex: 'operation',
      render: (operation: Operation) => {
        if (operation.code) {
          return (
            <div>
              {operation.entity.module.module}:{operation.entity.entity}:{operation.code}
            </div>
          );
        }
        return <div />;
      },
    },
    {
      title: '是否隐藏',
      dataIndex: 'isHidden',
      render: (hidden) => (
        <ProTag color={hidden ? 'error' : 'success'}>{hidden ? '是' : '否'}</ProTag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: 120,
      render: (status) => (
        <ProTag color={status === BasicStatus.DISABLE ? 'error' : 'success'}>
          {status === BasicStatus.DISABLE ? '禁用' : '启用'}
        </ProTag>
      ),
    },
    { title: '排序', dataIndex: 'sort', width: 60 },
    {
      fixed: 'right',
      title: '操作',
      key: 'operation',
      align: 'center',
      width: 100,
      render: (_, record) => (
        <div className="flex w-full justify-end text-gray">
          {record?.type !== MenuType.BUTTON && hasPermission('SECURITY:MENU:CREATE') && (
            <TipIconButton
              onClick={() => onCreate(record)}
              tipText={`为 <${record.name}> 新增目录、菜单或按钮`}
            >
              <Iconify icon="gridicons:add-outline" size={18} />
            </TipIconButton>
          )}
          {hasPermission('SECURITY:MENU:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText={`修改${record.name}`}>
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}
          {hasPermission('SECURITY:MENU:DELETE') && (
            <Popconfirm
              title={`确定要删除 <${record.name}> 吗？${
                record.children
                  ? `点击确定将删除 <${record.name}> 以及 <${record.name}> 下级所有内容。`
                  : ''
              }`}
              okText="确定"
              cancelText="取消"
              placement="left"
              onConfirm={() => {
                onDelete(record);
              }}
            >
              <TipIconButton tipText={`删除${record.name}`}>
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];

  const onCreate = (parent?: Menu | undefined) => {
    setMenuModalProps((prev) => ({
      ...prev,
      show: true,
      ...defaultMenuValue,
      title: '创建菜单',
      formValue: { ...defaultMenuValue, parent },
    }));
  };

  const onDelete = (record: Menu) => {
    menuService.deleteMenu(record.id!).then(() => {
      notification.success({ message: '删除成功' });
      menuService.menuList({}).then((res) => {
        setTableData(res);
      });
    });
  };

  const onEdit = (formValue: Menu) => {
    if (formValue.operation) {
      formValue.operationArray = [
        formValue.operation.entity.module.module,
        formValue.operation.entity.entity,
        formValue.operation.code,
      ];
    }
    setMenuModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改菜单',
      formValue,
    }));
  };
  return (
    <Card
      title="菜单管理"
      extra={
        hasPermission('SECURITY:MENU:CREATE') && (
          <Button type="primary" onClick={() => onCreate()}>
            创建
          </Button>
        )
      }
    >
      <Table
        rowKey="id"
        size="small"
        scroll={{ x: 'max-content' }}
        pagination={false}
        columns={columns}
        dataSource={tableData}
      />

      <MenuModal {...menuModalProps} />
    </Card>
  );
}
